package common.util.digestUtils.aes;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Arrays;

public class ImoocAES {

    private static String src = "{" +
            "\"appid\":\"00000051\",\"authcode\":\"134945269321836349\",\"body\":\"test\",\"cusid\": \"990581007426001\"," +
            "\"key\":\"allinpay888\"," +
            "\"randomstr\":\"dwada\",\"remark\":\"test\"," +
            "\"reqsn\": \"123123\"," +
            "\"trxamt\": \"1\"" +
            "}";

    public static void main(String[] args) {
        jdkAES();
    }

    public static void jdkAES() {
        try {
            //生成KEY
       /*     KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128);
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] keyBytes = secretKey.getEncoded();
            String base = Base64.encodeBase64String(keyBytes);
            System.out.printf(base);*/
            //key转换
            Key key = new SecretKeySpec(Base64.decodeBase64("4Ot4YORG5Jc1SwgBxVIZXA=="), "AES");
            System.out.println("秘钥字符串：" + new String(Base64.decodeBase64("4Ot4YORG5Jc1SwgBxVIZXA==")));
            System.out.println("秘钥字节" + Arrays.toString(Base64.decodeBase64("4Ot4YORG5Jc1SwgBxVIZXA==")));
            System.out.println("base64秘钥" + "4Ot4YORG5Jc1SwgBxVIZXA==");
            System.out.println("hex秘钥" + Hex.encodeHexString(Base64.decodeBase64("4Ot4YORG5Jc1SwgBxVIZXA==")));
            //加密
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(src.getBytes());
            System.out.println("hex加密: " + Hex.encodeHexString(result) + "长度" + Hex.encodeHexString(result).length());
            System.out.println("base64加密: " + Base64.encodeBase64String(result) + "长度" + Base64.encodeBase64String(result).length());

            //解密
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result1 = cipher.doFinal(Hex.decodeHex(Hex.encodeHexString(result).toCharArray()));
            byte[] result2 = cipher.doFinal(Base64.decodeBase64(Base64.encodeBase64String(result)));
            System.out.println("hex 解密: " + new String(result1));
            System.out.println("base64 解密: " + new String(result2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void bcAES() {
        jdkAES();
    }

}
